package com.itheima.api.array.demo01;

public class ArrayDemo01 {

    public static void main(String[] args) {


        int[] arr = {23 , 45 , 89 , 100 , 11} ;
        int index = baseSearch(arr, 11);
        System.out.println(index);

        System.out.println("=======================");

        int[] arr2 = {11 , 22 , 33 , 44 , 55 , 66 , 77 , 88 , 99 , 110 , 120} ;
        int index2 = binarySearch(arr2 , 99);
        System.out.println(index2);

    }

    public static int baseSearch(int[] arr , int key){

        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == key){
                return i;
            }
        }
        return -1;
    }

    public static int binarySearch(int[] arr , int key){

        int minIndex = 0;
        int maxIndex = arr.length - 1;
        int midIndex = (minIndex + maxIndex) / 2;

        while (minIndex <= maxIndex) {

            if (arr[midIndex] == key) {
                return midIndex;
            } else if (arr[midIndex] > key) {
                maxIndex = midIndex - 1;
            } else {
                minIndex = midIndex + 1;
            }

            midIndex = (minIndex + maxIndex) / 2;
        }
        return midIndex;
    }

}
